package org.example.im;

import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import org.example.Attributes;

import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

// 会话工具，维护 用户信息、连接对应的绑定关系
public class SessionUtil {
    private static final Map<String, Channel> userChannelMap = new ConcurrentHashMap<>();
    private static final Map<String, ChannelGroup> channelGroupMap = new ConcurrentHashMap<>();

    /**
     * 绑定用户和连接的关系
     * @param userId
     * @param channel
     */
    public static void bindChannel(String userId, Channel channel){
        userChannelMap.put(userId, channel);
        // 记录登录状态
        channel.attr(Attributes.SESSION).set(userId);
    }

    /**
     * 判断是否已经登录
     * @param channel
     * @return
     */
    public static boolean hasLogin(Channel channel){
        return channel.hasAttr(Attributes.SESSION);
    }

    /**
     * 解除用户与连接的绑定关系
     * @param channel
     */
    public static void unBind(Channel channel){
        userChannelMap.remove(channel.attr(Attributes.SESSION).get());
        channel.attr(Attributes.SESSION).set(null);
    }

    /**
     * 获取当前连接的用户
     * @param channel
     * @return
     */
    public static String getUserId(Channel channel){
        return channel.attr(Attributes.SESSION).get();
    }

    /**
     * 根据 用户id 获取连接对象
     * @param userId
     * @return
     */
    public static Channel getChannel(String userId){
        return userChannelMap.get(userId);
    }

    /**
     * 获取用户id随机5位字符
     */
    public static String randomUserId(){
        String STR = "abcdefghjklmnopqrstuvwxyz0123456789";
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < 5; i++) {
            Random random = new Random();
            int idx = random.nextInt(35);
            result.append(STR.charAt(idx));
        }
        return result.toString();
    }

    public static void saveGroup(String gropId, ChannelGroup channelGroup){
        channelGroupMap.put(gropId, channelGroup);
    }

    public static ChannelGroup getGroup(String gropId){
        return channelGroupMap.get(gropId);
    }
}
